import Vue from "vue";
import { transformData } from '@/libs/util';
import axios from "axios";
import router from "@/router";

export function revoke (data) {
  confirmExecutor.handleConfirm({
    type: `confirm`,
    url: `/quotation/recall`,
    data: data,
    transform: { quotationId: "quotationId" },
    preset: { label: "撤回报价单", requestType: true, mode: true }
  });
}

export function agree (data) {
  confirmExecutor.handleConfirm({
    type: `confirm`,
    url: `/quotation/agree`,
    data: data,
    transform: { quotationId: "quotationId" },
    preset: { label: "同意报价", requestType: true, mode: true }
  });
}

export function reject (data) {
  promptExecutor.schedule({
    type: `prompt`,
    url: `/quotation/reject`,
    data: data,
    transform: { quotationId: "quotationId" },
    preset: {
      label: "拒绝报价",
      requestType: true,
      name: "reason",
      mode: true
    }
  });
}

class PromptExecutor {
  constructor() { }
  parseUrl (url, data) {
    if (!url || !data) {
      return url;
    }

    for (let [name, value] of Object.entries(data)) {
      let pattern = "${" + name + "}";
      url = url.replace(pattern, value);
    }
    return url;
  }
  async confirm ({ url, data, preset, transform, value }, context) {
    let parsedUrl = this.parseUrl(url, data);
    let response = null;
    if (preset && preset.requestType) {
      response = await axios.put(
        parsedUrl,
        Object.assign({ [preset.name]: value }, transformData(data, transform))
      );
      /* {mode} 详情页面需要关闭当前页 */
      if (preset.mode) {
        Vue.prototype.$message({ type: "success", message: "操作成功" });
        router.back();
      }
    } else {
      response = await axios.post(
        parsedUrl,
        Object.assign({ [preset.name]: value }, transformData(data, transform))
      );
      /* {mode} 详情页面需要关闭当前页 */
      if (preset.mode) {
        Vue.prototype.$message({ type: "success", message: "操作成功" });
        router.back();
      }
    }
    // let response = await axios.post(parsedUrl, Object.assign({ [preset.name]: value }, transformData(data, transform)));
    context.search();
    Vue.prototype.$message({ type: "success", message: "操作成功" });
    return response;
  }

  schedule ({ url, data, preset, transform }) {
    Vue.prototype
      .$prompt("", `${preset.label}` || "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "textarea",
        inputPattern: /^.{1,200}$/,
        inputPlaceholder: `请输入${preset.label}`,
        inputErrorMessage: `${preset.label}不能为空,且不能超过200个字符`
      })
      .then(({ value }) => {
        this.confirm({ url, data, preset, transform, value });
      })
      .catch(() => { });
  }
}

class ConfirmExecutor {
  constructor() { }
  parseUrl (url, data) {
    if (!url || !data) {
      return url;
    }
    for (let [name, value] of Object.entries(data)) {
      let pattern = "${" + name + "}";
      url = url.replace(pattern, value);
    }
    return url;
  }
  async confirm ({ url, data, preset, transform }) {
    let parsedUrl = this.parseUrl(url, data);
    let response = null;
    if (preset && preset.requestType) {
      response = await axios.put(parsedUrl, transformData(data, transform));
    } else {
      response = await axios.post(parsedUrl, transformData(data, transform));
    }
    if (response.code === 0) {
      Vue.prototype.$nextTick(() => {
        // setTimeout(() => {
        //   asyncLoadSearch();
        // }, 1000);
        Vue.prototype.$message({ type: "success", message: "操作成功" });
        /* {mode} 详情页面需要关闭当前页 */
        if (preset.mode) {
          router.back();
        }
      });
      return response;
    }
  }
  handleConfirm ({ url, data, preset, transform }) {
    Vue.prototype
      .$confirm(
        `${preset?.custom ? preset.label : "确认" + preset.label}?`,
        "提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
      .then(() => {
        this.confirm({ url, data, preset, transform });
      });
  }
}

const promptExecutor = new PromptExecutor();
const confirmExecutor = new ConfirmExecutor()

// 费用保留2位小数
export function calculateTotalFees (fees) {
  return fees.map(fee => {
    const num = parseFloat(fee, 10) || 0;
    return num;
  }).reduce((total, num) => total + num, 0).toFixed(2);
}

/* 报价费用总数 */
export function totalFee ({ minimumFee, taxFee = 0, insureFee = 0, fees }) {
  if (minimumFee) {
    return minimumFee + taxFee + insureFee;
  } else {
    return calculateTotalFees(fees);
  }
}

function addTypeDisabledSurchargeFees (surchargeFees) {
  return surchargeFees?.map(item => ({
    ...item,
    typeDisabled: true
  })) || [];
}

const updateAuditingFees = (fees) => {
  return fees?.map(item => ({
    ...item,
    typeDisabled: false,
    barginDisabled: true,
    disabled: true
  }));
}

/* 第一次报价或审核报价通过
* mark 代表第一次报价 或者 审核报价通过的标识  这个标识是配置的 不是详情接口字段
*/
export function firstQuoteStrategy ({ data, status, mark }) {
  return data?.surchargeFees?.map(item => {
    if (status !== 0) {
      return { ...item, barginDisabled: true };
    } else if (mark) {
      return { ...item, typeDisabled: true };
    } else {
      return item;
    }
  });
}

/* 被拒绝费用 */
export function rejectedFeesStrategy ({ data }) {
  const modifiedSurchargeFees = addTypeDisabledSurchargeFees(data?.surchargeFees)
  const rejectedTip = { title: "被拒绝", typeDisabled: true, typeName: "【被拒绝】" };
  return [
    ...modifiedSurchargeFees,
    ...data?.rejectedFees,
    rejectedTip,
  ]
}

/* 待审核费用 */
export function auditingFeesStrategy ({ data, surcharge }) {

  const { surchargeFees = [], auditingFees = [] } = data || {};
  const auditTip = { title: "待审核", typeDisabled: true, typeName: "【待审核】" };
  let modifiedAuditingFees = []

  const modifiedSurchargeFees = addTypeDisabledSurchargeFees(surchargeFees)

  // 待审核的补充费用明细 
  if (surcharge) {
    modifiedAuditingFees = updateAuditingFees(auditingFees) || []
  }

  return [
    ...modifiedSurchargeFees,
    ...modifiedAuditingFees,
    auditTip
  ];
}

export function bargainFeesStrategy ({ data }) {
  /* 议价费用  发起方*/
  const modifiedSurchargeFees = addTypeDisabledSurchargeFees(data?.surchargeFees)
  const bargainTip = { title: "议价", typeDisabled: true, typeName: "【议价】" };
  if (data?.surchargeFees?.length) {
    return [
      ...modifiedSurchargeFees,
      ...data?.bargainFees,
      bargainTip
    ]
  } else {
    return [...data?.bargainFees];
  }
}


function processFeesStrategy ({ data, surcharge, tipTitle, tipName, feesKey }) {
  const tip = { title: tipTitle, typeDisabled: true, typeName: tipName };
  let modifiedFees = [];

  const modifiedSurchargeFees = addTypeDisabledSurchargeFees(data?.surchargeFees);

  if (surcharge) {
    modifiedFees = updateAuditingFees(data?.[feesKey]) || [];
  }

  return [
    ...modifiedSurchargeFees,
    ...modifiedFees,
    tip
  ];
}

export function attachFeesStrategy ({ data, surcharge }) {
  if (data?.surchargeFees?.length) {
    return processFeesStrategy({
      data,
      surcharge,
      tipTitle: "待审核",
      tipName: "【待审核】",
      feesKey: "bargainFees"
    });
  } else {
    return [...data?.bargainFees];
  }
}


export function closedFeesStrategy ({ data, surcharge }) {
  if (data?.surchargeFees?.length) {
    return processFeesStrategy({
      data,
      surcharge,
      tipTitle: "已关闭",
      tipName: "【已关闭】",
      feesKey: "closedFees"
    });
  } else {
    return [...data?.closedFees];
  }
}


